import { getInfo, login, logout } from "@/api/login"
import { ACCESS_TOKEN, AREA_ID, USER_TYPE, ROLE_KEY, NICK_NAME } from '@/store/mutaction-types.js'

const user = {
	state: {
		token: '',
		areaId: '',
		userType: '',
		roleKey: [],
		nickName: ''
	},
	mutations: {
		SET_TOKEN: (state, token) => {
			state.token = token
		},
		SET_AREA: (state, areaId) => {
			state.areaId = areaId
		},
		SET_USERTYPE: (state, userType) => {
			state.userType = userType
		},
		SET_ROLE: (state, roleKey) => {
			state.roleKey = roleKey
		},
		SET_NAME: (state, nickName) => {
			state.nickName = nickName
		}
	},
	actions: {
		Login({ commit }, data) {
			return new Promise((resolve, reject) => {
				login(data).then(res => {
					uni.setStorageSync(ACCESS_TOKEN, res.data.token, 60 * 60 * 24 * 7)
					commit('SET_TOKEN', res.data.token)
					resolve(res)
				}).catch(error => {
					reject(error)
				})
			})
		},
		GetInfo ({ commit, state }) {
			return new Promise((resolve, reject) => {
				getInfo(state.token).then(res => {
					const data = res.data
					uni.setStorageSync(AREA_ID, data.user.areaId, 60 * 60 * 24 * 7)
					uni.setStorageSync(ROLE_KEY, data.roles, 60 * 60 * 24 * 7)
					uni.setStorageSync(NICK_NAME, data.user.nickName, 60 * 60 * 24 * 7)
					commit('SET_AREA', data.user.areaId)
					commit('SET_ROLE', data.roles)
					commit('SET_NAME', data.user.nickName)
					resolve(res)
				}).catch(error => {
					reject(error)
				})
			})
		},
		Logout({ commit, state }) {
			return new Promise((resolve) => {
				logout(state.token).then(() => {
					commit('SET_TOKEN', '')
					commit('SET_AREA', '')
					commit('SET_ROLE', '')
					commit('SET_NAME', '')
					uni.removeStorageSync(ACCESS_TOKEN)
					uni.removeStorageSync(AREA_ID)
					uni.removeStorageSync(ROLE_KEY)
					uni.removeStorageSync(NICK_NAME)
					resolve()
				}).catch(error => {
					console.log('logout fail:', error)
				})
			})
		}
	}
}

export default user
